<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="description" content="">
		<meta name="author" content="">
		<title>出售商品</title>
		<link rel="stylesheet" href="../../css/base.css" />
		<script src="../../sbadmin/bower_components/jquery/dist/jquery.min.js"></script>
		<script type="text/javascript" src="../../js/weditor/aliyun-oss-sdk.js"></script>
	</head>

	<body>
		<div class="form-group">
			<label>Select file</label>
			<input type="file" id="file" />
		</div>
		<div class="form-group">
			<label>Store as</label>
			<input type="text" class="form-control" id="object-key-file" value="object" />
		</div>
		<div class="form-group">
			<input type="button" class="btn btn-primary" id="file-button" value="Upload" />
		</div>
		<div class="form-group">
			<div class="progress">
				<div id="progress-bar" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em;">
					0%
				</div>
			</div>
		</div>
	</body>
	<script>
		const applyTokenDo = function(func) {
			$.ajax({
				url: "https://order.wz1996.wang/wzbg/media/sts",
				type: 'get',
				success: function(data) {
					console.log(data)
					const client = new OSS({
						region: 'wangzheng1996.oss-cn-shanghai.aliyuncs.com',
						accessKeyId: data.data.credentials.accessKeyId,
						accessKeySecret: data.data.credentials.accessKeySecret,
						stsToken: data.data.credentials.securityToken,
						bucket: 'wangzheng1996'
					});
					return func(client);
				}
			});
		};
		let currentCheckpoint;
		const progress = async function progress(p, checkpoint) {
			currentCheckpoint = checkpoint;
			const bar = document.getElementById('progress-bar');
			bar.style.width = `${Math.floor(p * 100)}%`;
			bar.innerHTML = `${Math.floor(p * 100)}%`;
		};
		let uploadFileClient;
		const uploadFile = function(client) {
			if(!uploadFileClient || Object.keys(uploadFileClient).length === 0) {
				uploadFileClient = client;
			}
			const file = document.getElementById('file').files[0];
			const key = document.getElementById('object-key-file').value.trim() || 'object';
			console.log(`${file.name} => ${key}`);
			const options = {
				progress,
				partSize: 100 * 1024,
				meta: {
					year: 2017,
					people: 'test',
				},
			};
			return client.multipartUpload(key, file, options).then((res) => {
				console.log('upload success: %j', res);
				currentCheckpoint = null;
				uploadFileClient = null;
			}).catch((err) => {
				if(uploadFileClient && uploadFileClient.isCancel()) {
					console.log('stop-upload!');
				} else {
					console.error(err);
				}
			});
		};
		window.onload = function() {
			document.getElementById('file-button').onclick = function() {
				applyTokenDo(uploadFile);
			}
		};
	</script>

</html>